<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Community\Status;
use App\Models\Topic\Topic;
use App\Models\Topic\Reply;
use App\Models\Goods\Product;
use App\Models\Users\UserAddress;
use App\Models\Goods\CartItem;
use Auth;
use Encore\Admin\Traits\DefaultDatetimeFormat;
class User extends Authenticatable
{
    use Traits\User\ActiveUserHelper,Traits\User\LastActivedAtHelper,DefaultDatetimeFormat,HasApiTokens,HasFactory,Notifiable;
    use Notifiable {
        notify as protected laravelNotify;
    }

    protected $fillable = [
        'name',
        'avatar',
        'email',
        'password',
        'introduction'
    ];


    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function statuses()
    {
        return $this->hasMany(Status::class)->where('status',Status::StatusSuccess);
    }
    public function gravatar($size = '100')
    {
        return "https://cdn.learnku.com/uploads/avatars/32535_1543203834.jpeg!/both/100x100";
    }
    public function followers()
    {
        return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id');
    }
    public function followings()
    {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id');
    }
    public function topics()
    {
        return $this->hasMany(Topic::class)->where('status',Topic::StatusSuccess);
    }
    public function replies()
    {
        return $this->hasMany(Reply::class);
    }
    public function addresses()
    {
        return $this->hasMany(UserAddress::class)->where('status',UserAddress::StatusSuccess);
    }
    public function favoriteProducts()
    {
        return $this->belongsToMany(Product::class, 'user_favorite_products')
            ->withTimestamps()
            ->orderBy('user_favorite_products.created_at', 'desc');
    }
    public function cartItems()
    {
        return $this->hasMany(CartItem::class);
    }
    /*
     * 是否关注
     * */
    public function isFollowing($user_id)
    {
        return $this->followings->contains($user_id);
    }
    public function isAuthorOf($model)
    {
        return $this->id == $model->user_id;
    }
    public function notify($instance)
    {
        // 如果要通知的人是当前用户，就不必通知了！
        if ($this->id == Auth::id()) {
            return;
        }

        // 只有数据库类型通知才需提醒，直接发送 Email 或者其他的都 Pass
        if (method_exists($instance, 'toDatabase')) {
            $this->increment('notification_count');
        }

        $this->laravelNotify($instance);
    }
    /*
     * 清除消息
     * */
    public function markAsRead()
    {
        $this->notification_count = 0;
        $this->save();
        $this->unreadNotifications->markAsRead();
    }
}
